package reseauSocial;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import main.SYRRES;
import core.SetUser;
import core.User;

public class Similarity {
	private SetUser allUser;
	private float[] note_coeff;
	
	public Similarity(SetUser allUser, float[] note_coeff) {
		this.allUser = allUser;
		this.note_coeff = note_coeff;
	}
	
	public void calculSimilarity(int threshold, boolean withWeights) throws IOException {
		float similarity = 0;
		BufferedWriter bw = new BufferedWriter(new FileWriter("output/similarite" + threshold + ".txt"));
    	
		for (int i = 0; i < allUser.size(); i++) 
		for (int j = i + 1; j < allUser.size(); j++) {
			similarity = calSim(allUser.getUser(i), allUser.getUser(j));

			if (similarity > threshold) {
				if (withWeights) {
//					bw.write(allUser.getUser(i).getId() + " " + allUser.getUser(j).getId() + " " + similarity + "\n");		    	
					bw.write(i + " " + j + " " + (int)similarity + "\n");
				} else {
//					bw.write(allUser.getUser(i).getId() + " " + allUser.getUser(j).getId() + "\n");
					bw.write(i + " " + j + "\n");
				}
			}
		}
		
		bw.close();
	}
	
	public float calSim(User u1, User u2) {
		float similarity = 0;		
		
		HashMap<String, List<Integer>> biere_note1 = u1.getBiereNote();
		HashMap<String, List<Integer>> biere_note2 = u2.getBiereNote();

		int numOfBiere = biere_note1.size() + biere_note2.size();		
		for (String b1 : biere_note1.keySet()) {
			for (String b2 : biere_note2.keySet()) {
				if (b1.equals(b2)) {
					numOfBiere--;
					for (int i = 0; i < SYRRES.NB_NOTE; i++) {
						if (biere_note1.get(b1).get(i).equals(biere_note2.get(b2).get(i))) {
							similarity += 1 * note_coeff[i];
						}
					}
				}
			}
		}

//		similarity = (int)((float)similarity / (numOfBiere * SYRES.NB_NOTE) * 100);
		similarity = (int)((float)similarity / (numOfBiere * getSumOfArray(note_coeff)) * 100);
		return similarity;
	}
	
	public float getSumOfArray(float[] array) {
		float sum = 0;
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}
		return sum;
	}
}